<?php

namespace App\Http\Controllers\Order;

use App\Http\Controllers\BaseController;
use App\Models\Order\Contractorder;
use App\Models\Order\Contractordersub;
use App\Models\Order\Outboundorder;
use App\Models\Order\Outboundordersub;
use App\Models\Order\Saleorder;
use App\Models\Settle\SettleCompany;
use App\Models\Template\TemplateContractsStamp;
use App\Services\Common\SnCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 合同汇总
 */
class ContractController extends BaseController
{
    /**
     * 汇总合同
     */
    public function dopostadd(Request $request)
    {
        $ids = $request->ids;
        $idsarr = explode(',', $ids);
        //订单
        $order = Outboundorder::whereIn('id', $idsarr)->orderBy('document_date', 'asc')->get()->toArray();
        //同一客户同一结算公司 可以生成合同
        if(empty($order)){
           return response()->json(["code"=>"001","msg"=>"请求数据异常"]);
        }
        $custom_settlement_company = "";
        foreach ($order as $key=>$item){
            if($key == 0){
                $custom_settlement_company = $item["custom_id"].$item["settlement_company"];
                continue;
            }
            if($custom_settlement_company != $item["custom_id"].$item["settlement_company"]){
                return response()->json(["code"=>"001","msg"=>"合并的客户和结算公司必须一致"]);
            }
        }

        $start_document_date = $order[0]['document_date'];
        $end_document_date = $order[count($idsarr) - 1]['document_date'];

        //子订单
        $order_sub = Outboundordersub::whereIn('p_id', $idsarr)->get()->toArray();

        // $saleInfo = Saleorder::where('order_number', $req_data['order_number'])->first()->toArray();
        /***
         *
         * 同一客户同一结算公司,一段时间内，相同的钢材合并 2025.03.13
         *
         *
        **/
        if ($order_sub) {
            $order_sub_new = [];
            foreach ($order_sub as $key => $item) {
                if (!isset($order_sub_new[$item['archive_no']])){
                    //$archive_no_arr[] = $item['archive_no'];
                    $order_sub_new[$item['archive_no']] = [
                        "archive_no" => $item['archive_no'],
                        //"warehouse_name"=>$item['warehouse_name'],
                        "steel_factory_name"=>$item['steel_factory_name'],
                        "unit_price"=>$item['unit_price'],
                        "material_id"=>$item['material_id'],
                        "archive_name"=>$item['archive_name'],
                        "archive_spec"=>$item['archive_spec'],
                        "archive_material"=>$item['archive_material'],
                        "breed_name"=>$item['breed_name'],
                        "weight"=>$item['weight'],
                        "pieces"=>$item['pieces'],
                        "total"=>$item['total'],
                    ];
                }else{
                    $order_sub_new[$item['archive_no']]["weight"] += $item['weight'];
                    $order_sub_new[$item['archive_no']]["pieces"] += $item['pieces'];
                    $order_sub_new[$item['archive_no']]["total"] += $item['total'];
                }
            }
        }

        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;
        $manger_name = $mangerinfo['realname'] ?? '';

        $wagon_number = $driver_phone_number = '';
        foreach ($order as $itme) {
            $wagon_number = $itme['wagon_number'] . ',';
            $driver_phone_number = $itme['driver_phone_number'] . ',';
        }
        $wagon_number = rtrim($wagon_number, ',');
        $driver_phone_number = rtrim($driver_phone_number, ',');

        DB::beginTransaction();
        try {
            $data = [
                'cpid' => $cpid,
                'manger_id' => $manger_id,
                'manger_name' => $manger_name,
                'document_number' => SnCode::getSnCode('HT_'),
                'start_document_date' => $start_document_date,
                'end_document_date' => $end_document_date,
                'document_date' => time(),
                'bill_type' => $order[0]['bill_type'],
                'business_type' => $order[0]['bill_type'],
                'custom_id' => $order[0]['custom_id'],
                'custom_name' => $order[0]['custom_name'],
                'settlement_company' => $order[0]['settlement_company'],
                'contract_code' => SnCode::getSnCode('HZ_'),
                'wagon_number' => $wagon_number,
                'driver_phone_number' => $driver_phone_number,
                'create_at' => time(),
            ];
            $id = Contractorder::create($data)->id;
            foreach ($order_sub_new as $archive_no => $archive_item) {
                Contractordersub::create($archive_item + [
                    'cpid' => $cpid,
                    'p_id' => $id,
                    'manger_id' => $manger_id,
                    'manger_name' => $manger_name,
                    'create_at' => time(),
                    'individ_weight' => mathfuncweight('div',$archive_item['weight'],$archive_item['pieces'])

                ]);
            }
            //更新出库单
            Outboundorder::whereIn('id', $idsarr)->update(['is_create_contract'=>'2']);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '添加失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 列表
     */
    public function getlist(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $isgetall = $request->isgetall ?? 0;
        $list = Contractorder::getList($request, $memberinfo, $isgetall);
        if ($list['list']) foreach ($list['list'] as $key => $value) {
            foreach ($value['suborder'] as $k => $v) {
                $list['list'][$key]['suborder'][$k]['weight'] = $v['weight'] / 10000;
                $list['list'][$key]['suborder'][$k]['individ_weight'] = $v['individ_weight'] / 10000;
                $list['list'][$key]['suborder'][$k]['total'] = $v['total'] / 100;
            }
            if (is_numeric($value['settlement_company'])) {
                $settlement_company = SettleCompany::where([['id', (int)$value['settlement_company']]])->first();
                if ($settlement_company) {
                    $settlement_company = $settlement_company->toArray();
                    $list['list'][$key]['settlement_company'] = $settlement_company['settle_company_name'];
                } else {
                    $list['list'][$key]['settlement_company'] = '';
                }
            } else {
                $list['list'][$key]['settlement_company'] = $value['settlement_company'];
            }
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 详情
     */
    public function getone(Request $request)
    {
        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;

        $id = $request->id ?? 0;
        $one = Contractorder::getone($id);
        if ($one->isEmpty()) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }
        $one = $one->toArray();
        if (isset($one[0]['suborder'])) {
            foreach ($one[0]['suborder'] as $key => $value) {
                $one[0]['suborder'][$key]['weight'] = $value['weight'] / 10000;
                $one[0]['suborder'][$key]['total'] = $value['total'] / 100;
            }
        }
        if(isset($one[0]['settlement_company'])){
            $one[0]['settle_company_info'] = SettleCompany::where(['settle_company_name'=>$one[0]['settlement_company'],'cpid'=>$cpid])->first();
        }
        //合同印章获取
        $one[0]['seal_filepath'] = null;
        if (isset($one[0]['settle_company_info']['id'])) {
            $one[0]['seal_filepath'] = TemplateContractsStamp::where(['company_id' => $one[0]['settle_company_info']['id'], 'cpid' => $cpid, 'status' => '1'])->value('seal_filepath');
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $one]);
    }
}
